using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Jerry.UiFrame
{
    public class JListGrid : Selectable, IComponent
    {
        [SerializeField] [Header("选中时候的Image")]
        private Image selected;

        internal JList.JItemDelegate OnItemClick;
        internal JList.JItemDelegate OnItemDown;

        internal int Index { set; get; }

        internal RectTransform RectTransform => transform as RectTransform;

        internal JList Owner;
        private object _data;
        private bool _bSelected;
        
        [Obsolete("Use GetChild<T>(string childName) instead.")]
        public IComponent GetChild(string childName)
        {
            var comp = transform.Find(childName).GetComponent<IComponent>();
            return comp;
        }
        
        public T GetChild<T>(string childName) where T : IComponent
        {
            var comp = transform.Find(childName).GetComponent<IComponent>();
            return (T)comp;
        }

        //
        public override void OnPointerDown(PointerEventData eventData)
        {
            OnItemDown?.Invoke(this, Index);
            base.OnPointerDown(eventData);
        }

        //
        public override void OnPointerUp(PointerEventData eventData)
        {
            if (Owner.BDragging || Owner.BScrolling)
            {
                return;
            }

            OnItemClick?.Invoke(this, Index);
            Owner.Selected = Index;
            base.OnPointerUp(eventData);
           
            if (selected == null)
                return;

            Owner.ItemClick(this);
            if (Owner.multiple)
            {
                _bSelected = !_bSelected;
            }
            else
            {
                _bSelected = true;
            }

            if (selected.gameObject.activeSelf && Owner.singleOff)
            {
                _bSelected = false;
            }

            selected.gameObject.SetActive(_bSelected);
            selected.raycastTarget = false;
        }

        public void SetVisible(bool bVisible)
        {
            gameObject.SetActive(bVisible);
        }

        /// <summary>
        /// 设置Grid的选中状态
        /// </summary>
        internal void SetSelectedState(bool bUnSelected)
        {
            if(selected == null)
                return;
            selected.gameObject.SetActive(bUnSelected);
        }
    }
}